package com.crm.business.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.crm.business.admin.service.AdminService;
import com.crm.business.admin.service.IAdminDeptService;
import com.crm.business.admin.service.IAdminUserManageDeptService;
import com.crm.business.admin.service.IAdminUserService;
import com.crm.business.crm.mapper.CrmRoiPutinMapper;
import com.crm.business.crm.service.*;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.ActionRecordUtil;
import com.crm.business.utils.UserCacheUtil;
import com.crm.business.utils.UserUtil;
import com.crm.common.admin.entity.PO.AdminDept;
import com.crm.common.admin.entity.VO.AdminUserVO;
import com.crm.common.crm.constant.*;
import com.crm.common.crm.entity.BO.*;
import com.crm.common.crm.entity.PO.*;
import com.crm.common.crm.entity.VO.*;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 投放消耗表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-05-21
 */
@Service
@Slf4j
public class CrmRoiPutinServiceImpl extends BaseServiceImpl<CrmRoiPutinMapper, CrmRoiPutin> implements ICrmRoiPutinService, CrmPageService {

    @Autowired
    private ActionRecordUtil actionRecordUtil;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ICrmRoiStatisService crmRoiStatisService;

    @Autowired
    private IAdminUserService adminUserService;

    @Override
    public String[] appendSearch() {
        return new String[0];
    }

    @Override
    public void setOtherField(Map<String, Object> map) {

    }

    @Override
    public CrmEnum getLabel() {
        return null;
    }

    @Override
    public List<CrmModelFiledVO> queryDefaultField() {
        return null;
    }

    public BasePage<CrmRoiPutin> queryPageList(CrmRoiPutinPageBO crmRoiPutinPageBO){

        List<Integer> allDeptIds = new ArrayList<>();

        if(crmRoiPutinPageBO.getIsAuth() == 1){
            List<AdminDept> manageDeptList = SpringUtils.getBean(IAdminUserManageDeptService.class).queryManageDeptListByUserId(UserUtil.getUserId());
            List<Integer> manageDeptIdList = manageDeptList.stream().map(AdminDept::getDeptId).collect(Collectors.toList());
            for(Integer deptId : manageDeptIdList){
                allDeptIds.addAll(SpringUtils.getBean(IAdminDeptService.class).queryChildDept(deptId));
                allDeptIds.add(deptId);
            }

            allDeptIds.add(UserUtil.getUser().getDeptId());
            allDeptIds.addAll(SpringUtils.getBean(IAdminDeptService.class).queryChildDept(UserUtil.getUser().getDeptId()));
            allDeptIds = allDeptIds.stream().distinct().collect(Collectors.toList());
        }else{
            allDeptIds.addAll(SpringUtils.getBean(IAdminDeptService.class).queryChildDept(0));
        }

        if(!CollectionUtils.isEmpty(crmRoiPutinPageBO.getDeptIds())){
            allDeptIds.retainAll(crmRoiPutinPageBO.getDeptIds());
        }else{
            crmRoiPutinPageBO.setDeptIdList(allDeptIds);
        }

        crmRoiPutinPageBO.setDeptIds(allDeptIds);

        List<Long> userList = new ArrayList<>();

        if(crmRoiPutinPageBO.getIsAuth() == 1){
            userList.addAll(SpringUtils.getBean(AdminService.class).queryUserIdsByRoleIds());
            //管理部门 数据权限
            List<Long> ManageDeptUserIdList = SpringUtils.getBean(AdminService.class).queryUserIdsByManageDept();
            userList.addAll(ManageDeptUserIdList);
            userList = userList.stream().distinct().collect(Collectors.toList());
        }else{
            List<AdminUserVO> adminUserBOList = adminUserService.queryUserList(null).getList();
            userList.addAll(adminUserBOList.stream().map(AdminUserVO::getUserId).collect(Collectors.toList()));
            userList = userList.stream().distinct().collect(Collectors.toList());
        }

        crmRoiPutinPageBO.setUserIdList(userList);

        BasePage<CrmRoiPutin> roiPutinBasePage = baseMapper.queryPageList(crmRoiPutinPageBO.parse(), crmRoiPutinPageBO);

        roiPutinBasePage.getList().forEach(item -> {
            // 创建人名称回显
            if(ObjectUtil.isNotEmpty(item.getCreateUserId())){
                String createUserName = UserCacheUtil.getUserName(item.getCreateUserId());
                item.setCreateUserName(createUserName);
            }
            // 更新人名称回显
            if(ObjectUtil.isNotEmpty(item.getUpdateUserId())){
                String updateUserName = UserCacheUtil.getUserName(item.getUpdateUserId());
                item.setUpdateUserName(updateUserName);
            }
            // 消耗部门名称回显
            if(ObjectUtil.isNotEmpty(item.getDeptId())){
                String deptName = adminService.queryAllDeptNameByDeptId(item.getDeptId());
                if(StringUtils.isNotBlank(deptName)){
                    deptName = deptName.replace("|","-");
                }
                item.setDeptName(deptName);
            }
        });

        Map<String, Object> sunMoney=new HashMap<>();
        BigDecimal putinMoney = baseMapper.queryListSumMoney(crmRoiPutinPageBO);
        sunMoney.put("putinMoneySum", String.valueOf(putinMoney));
        roiPutinBasePage.setExtraData(sunMoney);
        crmRoiStatisService.statisRoi();
        return roiPutinBasePage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdate(CrmRoiPutin crmRoiPutin) {
        if(crmRoiPutin.getPutinId() == null){
            crmRoiPutin.setCreateUserId(UserUtil.getUserId());
            crmRoiPutin.setCreateTime(new Date());
            save(crmRoiPutin);
            actionRecordUtil.addRecord(crmRoiPutin.getPutinId(), CrmEnum.ROI_PUTIN, crmRoiPutin.getPutinPlatform());
        }else{
            crmRoiPutin.setUpdateUserId(UserUtil.getUserId());
            crmRoiPutin.setUpdateTime(new Date());
            actionRecordUtil.updateRecord(BeanUtil.beanToMap(getById(crmRoiPutin.getPutinId())), BeanUtil.beanToMap(crmRoiPutin), CrmEnum.ROI_PUTIN, crmRoiPutin.getPutinPlatform(), crmRoiPutin.getPutinId());
            updateById(crmRoiPutin);
        }
    }

    @Override
    public List<Map<String,Object>> selectAllPutinStatis(){
        return baseMapper.selectAllPutinStatis();
    }

    @Override
    public BigDecimal querySumMoney(String putinPlatform,String startPutinFormDate,String endPutinFormDate){
        return baseMapper.querySumMoney(putinPlatform, startPutinFormDate, endPutinFormDate);
    }

    @Override
    public List<CrmRoiStatisVO> queryPutinStatisForData(String startPutinFormDate,String endPutinFormDate){
        return baseMapper.queryPutinStatisForData(startPutinFormDate, endPutinFormDate);
    }

    @Override
    public CrmRoiPutin getRoiDataById(Integer putinId){
        CrmRoiPutin roiPutin = baseMapper.selectById(putinId);
        if(ObjectUtil.isNotEmpty(roiPutin.getDeptId())){
            String deptName = adminService.queryAllDeptNameByDeptId(roiPutin.getDeptId());
            if(StringUtils.isNotBlank(deptName)){
                deptName = deptName.replace("|","-");
            }
            roiPutin.setDeptName(deptName);
        }
        // 创建人名称回显
        if(ObjectUtil.isNotEmpty(roiPutin.getCreateUserId())){
            String createUserName = UserCacheUtil.getUserName(roiPutin.getCreateUserId());
            roiPutin.setCreateUserName(createUserName);
        }
        // 更新人名称回显
        if(ObjectUtil.isNotEmpty(roiPutin.getUpdateUserId())){
            String updateUserName = UserCacheUtil.getUserName(roiPutin.getUpdateUserId());
            roiPutin.setUpdateUserName(updateUserName);
        }
        return roiPutin;
    }

    @Override
    public List<CrmRoiStatisVO> queryPutinStatisByFormDate(CrmRoiPutinPageBO crmRoiPutinPageBO){
        return baseMapper.queryPutinStatisByFormDate(crmRoiPutinPageBO);
    }

    @Override
    public List<CrmRoiStatisVO> queryPutinStatisForYearsSource(String startPutinFormDate,String endPutinFormDate){
        return baseMapper.queryPutinStatisForYearsSource(startPutinFormDate, endPutinFormDate);
    }

}
